package com.mbc.web.common.client.ui;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import com.mbc.common.entities.Branch;
import com.mbc.common.entities.User;
import com.mbc.web.common.client.CommonControllerMgr;
import com.mbc.web.common.client.CommonMessage;
import com.mbc.web.common.client.ViewUtils;
import com.mbc.web.common.client.ui.control.MButton;
import com.mbc.web.common.client.ui.control.MListBox;
import com.mbc.web.common.client.ui.control.MTextBox;
import com.mbc.web.common.shared.HttpStatus;
import com.mbc.web.common.shared.dto.BranchListDTO;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.event.dom.client.KeyDownEvent;

public class FrmUserBranchChange extends Composite {

	@UiField MButton btnSave;
	@UiField MButton btnNew;
	@UiField MTextBox txtLoginId;
	@UiField Label lblUserName;
	@UiField MListBox listBranch;
	@UiField Button btnUserModal;
	
	private List<Branch> branchList;
	
	private static FrmUserBranchChangeUiBinder uiBinder = GWT
			.create(FrmUserBranchChangeUiBinder.class);

	interface FrmUserBranchChangeUiBinder extends
			UiBinder<Widget, FrmUserBranchChange> {
	}

	public FrmUserBranchChange() {
		initWidget(uiBinder.createAndBindUi(this));
		initialize();
	}

	private void initialize(){
		txtLoginId.getElement().setAttribute("style", "text-transform: uppercase;");
		Scheduler.get().scheduleDeferred(new ScheduledCommand() {
			
			@Override
			public void execute() {
				txtLoginId.setFocus(true);
				CommonControllerMgr.getAllBranch(getAllBranchCallback());
			}
		});
	}
	
	private AsyncCallback<BranchListDTO> getAllBranchCallback(){
		return new AsyncCallback<BranchListDTO>() {
			
			@Override
			public void onSuccess(BranchListDTO result) {
				if(result.getHttpStatus() == HttpStatus.OK){
					branchList = result.getBranchList();
					for (Branch l_br : branchList) {
						listBranch.addItem(l_br.getName(), String.valueOf(l_br.getBranchId()));
					}
				}
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}
		};
	}
	
	private void clear(){
		txtLoginId.setText("");
		listBranch.setSelectedIndex(0);
		lblUserName.setText("");
	}
	
	private boolean isValid(){
		ViewUtils.closeMessageBox();
		if(!ViewUtils.isValidate())
			return false;
		if(listBranch.getItemCount() == 0){
			ViewUtils.showErrorMessage("No branch.");
			return false;
		}
		return true;
	}
	
	private void bindControl(User user){
		lblUserName.setText(user.getUserName());
		if(user.getUserInOfficeList().size() > 0){
			txtLoginId.setText(user.getLoginId());
			for (int i = 0; i < listBranch.getItemCount(); i++) {
				if(listBranch.getValue(i).equals(String.valueOf(user.getUserInOfficeList().get(0).getOfficeId()))){
					listBranch.setSelectedIndex(i);
					break;
				}
			}
		}
	}
	
	@UiHandler("btnUserModal")
	void onBtnUserModalClick(ClickEvent event) {
		ViewUtils.closeMessageBox();
		final SearchUser l_searchUser = new SearchUser("User List");
		l_searchUser.showDialog(new CloseHandler<Modal>() {
			
			@Override
			public void onClose(CloseEvent<Modal> event) {
				if(l_searchUser.getSelectedEntity() != null){
					bindControl(l_searchUser.getSelectedEntity());
				}
			}
		});
	}
	
	@UiHandler("btnNew")
	void onBtnNewClick(ClickEvent event) {
		clear();
		txtLoginId.setFocus(true);
	}
	
	@UiHandler("btnSave")
	void onBtnSaveClick(ClickEvent event) {
		if(isValid()){
			ViewUtils.startAjaxLoader(CommonMessage.saving_message);
			CommonControllerMgr.changeUserBranch(txtLoginId.getText(), Long.parseLong(listBranch.getValue(listBranch.getSelectedIndex())), changeUserBranchCallback());
		}
	}
	
	private AsyncCallback<Integer> changeUserBranchCallback(){
		return new AsyncCallback<Integer>() {
			
			@Override
			public void onSuccess(Integer result) {
				ViewUtils.stopAjaxLoader();
				if(result == HttpStatus.OK){
					ViewUtils.showSuccessMessage(CommonMessage.saved_message);
					clear();
					txtLoginId.setFocus(true);
				} else if(result == HttpStatus.NOT_FOUND){
					ViewUtils.showErrorMessage(CommonMessage.getDataNotFoundMessage("Logind ID '" + txtLoginId.getText() + "'"));
				}
				else
					ViewUtils.showErrorMessage(CommonMessage.internal_server_error_message);
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}
		};
	}
	
	@UiHandler("txtLoginId")
	void onTxtLoginIdKeyDown(KeyDownEvent event) {
		if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER){
			if(!txtLoginId.getText().equals("")){
				ViewUtils.closeMessageBox();
				CommonControllerMgr.findUserByLoginId(txtLoginId.getText(), findUserByLoginIdCallback());
			}
		}
	}
	
	private AsyncCallback<User> findUserByLoginIdCallback(){
		return new AsyncCallback<User>() {
			
			@Override
			public void onSuccess(User result) {
				if(result == null){
					ViewUtils.showErrorMessage(CommonMessage.record_not_found);
				} else {
					bindControl(result);
				}
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}
		};
	}
}
